package com.syl.practice.globalException2.filter;

import com.syl.practice.globalException2.anno.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class ResponseResultIntercetor implements HandlerInterceptor {

    private final static String RESPONSE_RESULT_ANN = "RESPONSE_RESULT_ANN";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        if (o instanceof HandlerMethod) {
            HandlerMethod hanlder = (HandlerMethod) o;
            Class<?> aClass = hanlder.getBeanType();
            Method method = hanlder.getMethod();
            // 判断所在类对象是否有注解
            if (aClass.isAnnotationPresent(ResponseResult.class)) {
                httpServletRequest.setAttribute(RESPONSE_RESULT_ANN, aClass.getAnnotation(ResponseResult.class));
            } else if (method.isAnnotationPresent(ResponseResult.class)) {
                httpServletRequest.setAttribute(RESPONSE_RESULT_ANN, aClass.getAnnotation(ResponseResult.class));
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
